package com.example.demo.service;

import com.example.demo.dao.BookInfoMapper;
import com.example.demo.dao.OrderDetailMapper;
import com.example.demo.dao.OrderShippingMapper;
import com.example.demo.dao.OrdersMapper;
import com.example.demo.entity.*;
import com.example.demo.pay.PayContext;
import com.example.demo.pojo.BSResult;
import com.example.demo.utils.BSResultUtils;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.awt.print.Book;
import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderShippingMapper orderShippingMapper;

    @Autowired
    private BookInfoMapper bookInfoMapper;

    //未完成状态，比如未付款等
    private final int NOT_COMPLETED = 0;

    private final int COMPLETED = 1;

    //未发货
    private final int NOT_POST = 2;
    //已发货
    private final int POSTED = 3;

    //确认收货
    private final int CONFIRM_REVEIVE = 4;


    /**
     * 订单号生成
     *
     * @return
     */
    public static String genOrderId() {
        //取当前时间的长整形值包含毫秒
        //long millis = System.currentTimeMillis();
        long millis = System.nanoTime();
        //加上两位随机数
        Random random = new Random();
        int end2 = random.nextInt(99);
        //如果不足两位前面补0
        String str = millis + String.format("%02d", end2);
        return str;
    }


    @Override
    public BSResult createOrder(User orderUser, Cart cart, String express, Integer payMethod) {

        Map<Integer,CartItem> cartItems=cart.getCartItems();

        if(cartItems.size()>0) {
            //createOrder
            Orders order = new Orders();
            order.setOrderId(this.genOrderId());
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setUserId(orderUser.getUserId());
            order.setPayment(String.format("%.2f",cart.getTotal()));
            order.setPaymentType(payMethod);
            order.setShippingName(express);
            order.setOrderMount(cartItems.size());
            order.setBuyerRate(0);
            order.setStatus(NOT_COMPLETED);
            order.setPostFee("0.00");
            ordersMapper.insertSelective(order);

            //createOrderShipping
            OrderShipping orderShipping=new OrderShipping();
            orderShipping.setOrderId(order.getOrderId());
            orderShipping.setReceiverName(orderUser.getUsername());
            orderShipping.setReceiverMobile(orderUser.getPhone());
            orderShipping.setReceiverState(orderUser.getLocation());
            orderShipping.setReceiverCity(orderUser.getLocation());

            orderShipping.setReceiverAddress(orderUser.getDetailAddress());
            orderShipping.setReceiverZip(orderUser.getZipCode());
            orderShipping.setCreated(new Date());
            orderShipping.setUpdated(new Date());
            orderShippingMapper.insertSelective(orderShipping);


            //create OrderDetail
            for(Map.Entry<Integer,CartItem> entry:cartItems.entrySet()) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderNumber(order.getOrderId());
                orderDetail.setOrderId(order.getOrderId());

                Integer bookId=entry.getKey();
                CartItem cartItem=entry.getValue();
                BookInfo bookInfo=cartItem.getBookInfo();
                orderDetail.setBookId(bookId);
                orderDetail.setStoreId(bookInfo.getStore_id());
                orderDetail.setMount(cartItem.getBuyNum());
                orderDetail.setUnitPrice(bookInfo.getMarket_price());
                orderDetail.setTotalPrice(new BigDecimal(cartItem.getSubTotal()));
                orderDetail.setPostStatus("0");
                orderDetail.setReceiveStatus("0");
                orderDetail.setImageUrl(bookInfo.getImage_url());
                orderDetail.setBookName(bookInfo.getName());
                 orderDetailMapper.insertSelective(orderDetail);
            }
            return BSResultUtils.success(order);
        }else{

            return BSResultUtils.build(400,"订单生成失败");
        }

    }


    @Override
    public List<OrderCustom> findAllOrdersByUserId(Integer userId) {

        List<OrderCustom> orderCustoms=new ArrayList<>();

        Example ordersExample=new Example(Orders.class);
        Example.Criteria ordersCriteria=ordersExample.createCriteria();
        ordersCriteria.andEqualTo("userId",userId);
        List<Orders> orders=ordersMapper.selectByExample(ordersExample);

        for(Orders order:orders){

            //2
            OrderShipping orderShipping=orderShippingMapper.selectByPrimaryKey(order.getOrderId());

            //3
            Example example=new Example(OrderDetail.class);
            Example.Criteria criteria=example.createCriteria();
            criteria.andEqualTo("orderId",order.getOrderId());
            List<OrderDetail> orderDetails=orderDetailMapper.selectByExample(example);


            //4
            OrderCustom orderCustom=new OrderCustom();
            orderCustom.setOrderId(order.getOrderId());
            orderCustom.setOrder(order);
            orderCustom.setOrderShipping(orderShipping);
            orderCustom.setOrderDetails(orderDetails);

            //5
            orderCustoms.add(orderCustom);

        }

        return orderCustoms;
    }

    @Override
    @Transactional
    public int deleteOrdersByOrderId(String orderId) {

        ordersMapper.deleteByPrimaryKey(orderId);

        orderShippingMapper.deleteByPrimaryKey(orderId);

        Example example=new Example(OrderDetail.class);

        Example.Criteria criteria=example.createCriteria();

        criteria.andEqualTo("orderId",orderId);

        orderDetailMapper.deleteByExample(example);
        return 1;
    }

    @Override
    public BSResult findOrdersByOrderId(String orderId) {

        Orders orders=ordersMapper.selectByPrimaryKey(orderId);
        return BSResultUtils.success(orders);
    }


    @Override
    public BSResult updateOrdersAfterPay(PayContext payContext) {

        //update order
        Orders order=payContext.getOrder();
        order.setPaymentTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(COMPLETED);
        ordersMapper.updateByPrimaryKeySelective(order);

        //update store amount in bookinfo
        List<BookInfo> bookInfos=payContext.getBookInfos();

        for(BookInfo bookInfo:bookInfos){

            Example example=new Example(OrderDetail.class);
            Example.Criteria criteria=example.createCriteria();
            criteria.andEqualTo("orderId",order.getOrderId());
            OrderDetail orderDetail=orderDetailMapper.selectOneByExample(example);
            if(orderDetail!=null) {
                bookInfo.setStore_mount(bookInfo.getStore_mount() - orderDetail.getMount());
                //deal mount update
                bookInfo.setDeal_mount(bookInfo.getDeal_mount()+orderDetail.getMount());
                bookInfoMapper.updateByPrimaryKeySelective(bookInfo);
            }

        }
        return BSResultUtils.success();
    }

    @Override
    public int updateOrders(Orders order) {
        return ordersMapper.updateByPrimaryKeySelective(order);
    }



}
